package com.fanghaoran.notes.service.impl;

import com.fanghaoran.notes.bean.MyResult;
import com.fanghaoran.notes.dao.EvaluationDao;
import com.fanghaoran.notes.dao.ProductDao;
import com.fanghaoran.notes.dao.impl.EvaluationDaoImpl;
import com.fanghaoran.notes.dao.impl.ProductDaoImpl;
import com.fanghaoran.notes.entity.Evaluation;
import com.fanghaoran.notes.entity.SensitiveBase;
import com.fanghaoran.notes.service.EvaluationService;
import com.fanghaoran.notes.util.Constants;
import com.fanghaoran.notes.util.JdbcUtil;
import com.fanghaoran.notes.util.StringUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: win11
 * @Date: 2023/04/24/11:50
 * @Description:
 */
public class EvaluationServiceImpl implements EvaluationService {

    EvaluationDao evaluationDao=new EvaluationDaoImpl();
    ProductDao productDao=new ProductDaoImpl();

    @Override
    public MyResult showEvaluation(int iid) throws Exception {
        List<Evaluation> evaluations = evaluationDao.selectEvaluation(iid);
        return StringUtil.returnOfSelect(evaluations);
    }

    @Override
    public MyResult addEvaluation(int uid,int iid, int score,int pid, String comment) throws Exception {
        Connection connection=null;
        try{
            connection= JdbcUtil.getConnection();
            //开启事务
            connection.setAutoCommit(false);

            //对评价进行处理
            String regEx="[`~!@#$%^&*()+=|{}':;,\\[\\].<>/?！￥…（）—【】‘；：”“’。 ，、？]";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(comment);
            String dealComment = m.replaceAll("").trim();
            //数据库调用敏感词库进行检测
            List<SensitiveBase> sensitiveBases = evaluationDao.selectSensitiveBase();
            for (SensitiveBase sensitiveBase : sensitiveBases) {
                if(dealComment.contains(sensitiveBase.getSensitiveWord())){
                    return new MyResult(Constants.EXITS_SENSITIVE_WORDS,null);
                }
            }
            //插入评论数据
            evaluationDao.insertEvaluation(uid, iid, score, comment);
            //更新产品评分
            productDao.updateProductScoreByPid(pid);

            //提交事务
            connection.commit();
            return new MyResult(Constants.SUCCESS,null);
        }catch (SQLException e){
            //回滚事务
            if (connection != null) {
                connection.rollback();
            }
            return new MyResult(Constants.FAIL,"发生错误");
        }catch (Exception e2){
            e2.printStackTrace();
            return new MyResult(Constants.FAIL,"发生错误");
        } finally {
            //释放连接资源
            if (connection != null) {
                try {
                    JdbcUtil.freeConnection();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
